<?php

/**
 * Logger class.
 */
class Logger {
	const WARNING_LEVEL = 1;
	const DEBUG_LEVEL = 2;
	const ERROR_LEVEL = 3;

	public function _construct() {
	}

	/**
	 * Writes log. Depending on logLevel log files are different 
	 * If level is set to ERROR_LEVEL log is written in current error_log[DATE] file.
	 * Else in file defined in setup.inc by DEBUG_FILE_PATH variable.
	 * 
	 * @param unknown_type $message
	 * @param unknown_type $level
	 */
	public function addLog($message, $level = Logger::DEBUG_LEVEL) {			
		$startPart = "";
		switch($level) {
			case Logger::ERROR_LEVEL:
				$startPart = "ERROR";
				break;
			case Logger::DEBUG_LEVEL:
				$startPart = "DEBUG";
				break;
			case Logger::WARNING_LEVEL:
				$startPart = "WARNING";
				break;
			default:
				return;
				break;
		}

		$dateStr = date("y.m.d-H:i");
		$log =$startPart."[".$dateStr."]:".$message."\r\n";

		$logFile = $this->getLogFile($level);
		if($logFile != null) {
			file_put_contents($logFile, $log, FILE_APPEND);
		}
	}

	private function getLogFile($level) {
		if($level == Logger::DEBUG_LEVEL || $level == Logger::WARNING_LEVEL) {
			if(file_exists(DEBUG_FILE_PATH) && is_writable(DEBUG_FILE_PATH)) {
				return DEBUG_FILE_PATH;
			}
			return null;
		}
		else if($level == Logger::ERROR_LEVEL) {
			$logExists = $this->errorLogExists();
			if($logExists == false) {
				$logExists = $this->createErrorLogFile();
			}
			$errorLogFilePath = $this->getErrorLogFilePath();
			if($logExists == true && is_writable($errorLogFilePath)) {
				return $errorLogFilePath;
			}
			else {
				return null;
			}
		}
	}

	private function getErrorLogFilePath() {
		$dateStr = date("y_m_d");
		$logPath = LOG_FILE_PATH;
		$logParts = explode('.',$logPath);
		$logParts[count($logParts)-2] .= $dateStr;
		return implode('.',$logParts);		
	}	
	
	private function errorLogExists() {
		$logNameWithDate = $this->getErrorLogFilePath();
		if(file_exists($logNameWithDate)) {
			return true;
		} 
		return false;
	}

	private function createErrorLogFile() {
		$logNameWithDate = $this->getErrorLogFilePath();

		if(file_exists($logNameWithDate) == false) {
			$created = fopen($logNameWithDate, 'w');
			if($created == false) {
				return false;
			}
		}
		return true;
	}	
}
?>